#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
void ChildWrite(int wfd)
{
    char c = 0;
    //char buffer[1024];
    int cnt = 0;
    while (1)
    {
        //snprintf(buffer, sizeof(buffer), "%d I am child,pid = %d", cnt++, getpid());
        write(wfd, &c, 1);
        //sleep(1);
        printf("child: %d\n",cnt++);
        //break;
    }
}

void FatherRead(int rfd)
{
    char buffer[1024];
    while (1)
    {
        sleep(100);
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer) - 1); // 实际的大小    预留\0
        if(n > 0)
        {
            std::cout << "Child says:" << buffer << std::endl;
            buffer[n] = 0;
        }
        else if(n == 0)
        {
            std::cout << "n : " << n << std::endl;
            std::cout << "write(c) break, read(f) break!" << std::endl;
            break;
        }
        else
        {
            break;
        }
        break;
    }
}

int main()
{
    // 1.创建管道
    int fds[2] = {0}; // fds[0] 读端  fds[1]  写端
    int n = pipe(fds);
    if (n < 0)
    {
        std::cerr << "pipe err" << std::endl;
        return 1;
    }
    // 2.创建子进程
    pid_t id = fork();
    if (id == 0)
    {
        // child -> w  f -> r
        // 关闭子进程的读端
        close(fds[0]);
        ChildWrite(fds[1]);
        close(fds[1]);
    }
    // father
    close(fds[1]);
    FatherRead(fds[0]);
    close(fds[0]);
    int status = 0;
    int ret = waitpid(id, &status, 0);
    if(ret > 0)
    {
        printf("exit code: %d,exit signal: %d\n",(status>>8) & 0xFF,status & 0x7F);
    }
    return 0;
}